<!--
 * @Author: yuandawei
 * @Date: 2020-11-04 17:05:59
 * @LastEditTime: 2020-11-20 10:51:15
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \vue-admin-beautiful-pro-template\src\views\index\index.vue
-->
<template>
  <div class="counselor-container">
    <div class="wrapper">
      <HHsearch
        ref="search"
        :search-options="searchOptions"
        :btn-option="2"
        @search="search"
        @reset="reset"
        @export="handleExport"
      ></HHsearch>
      <HHtable
        ref="table"
        :border="true"
        :total="total"
        :table-data="tableData"
        :table-column="tableColumn"
        :btn-option="btnOption"
        @page-click="pageClick"
      >
        <template #codeSlot="{ data }">
          <img v-if="data.wxCode" :src="data.wxCode" alt="" class="imgs" />
          <img v-else src="@/assets/imgs/none.png" alt="" class="imgs" />
        </template>
        <template #remarkSlot="{ data }">
          <div class="remark-edit flex-center">
            <span v-if="data.isShow">{{ data.remarks || '无' }}</span>
            <el-tooltip v-else :content="value3" placement="top" effect="light">
              <el-input v-model="value3" placeholder="请输入内容"></el-input>
            </el-tooltip>
            <img
              v-if="data.isShow"
              src="@/assets/imgs/edit.png"
              alt=""
              style="margin-left: 10px"
              @click="editRemark(data)"
            />
            <img
              v-else
              src="@/assets/imgs/save.png"
              alt=""
              @click="saveRemark(data)"
            />
          </div>
        </template>
      </HHtable>
    </div>
    <modal
      title="冻结分销确认"
      :show-modal="showFreezeModal"
      @confirm="confirmFreeze(2)"
      @cancel="showFreezeModal = false"
    >
      <template #body>
        <div class="container">
          <div class="title">
            <div class="icon el-icon-warning"></div>
            <div class="message">确定冻结所选招生顾问的分销关系吗？</div>
          </div>
          <div class="bottom">
            <p>说明：</p>
            <p>1、客户下单后订单归属机构，招生顾问不再分佣；</p>
            <p>2、被冻结期间，通过链接、二维码等途径新增的客户，均归机构所有</p>
            <p>3、被冻结前的客户关系保持不变，解冻后恢复正常；</p>
            <p>4、冻结期间，招生顾问的累计积分和相关订单金额不会自动变更。</p>
          </div>
        </div>
      </template>
    </modal>
    <modal
      title="解冻分销确认"
      :show-modal="showUnfreezeModal"
      @confirm="confirmFreeze(1)"
      @cancel="showUnfreezeModal = false"
    >
      <template #body>
        <div class="container">
          <div class="title">
            <div class="icon el-icon-warning"></div>
            <div class="message">确定解冻所选分销员的分销关系吗？</div>
          </div>
          <div class="bottom">
            <p>说明：</p>
            <p>1、解冻分销后，原客户关系恢复正常；</p>
          </div>
        </div>
      </template>
    </modal>
    <el-dialog
      :visible.sync="dialogVisible"
      width="40%"
      title="修改关系"
      :lock-scroll="false"
    >
      <el-row>
        <el-col :span="24">
          <el-radio-group v-model="radio" @change="handleRadioChange">
            <el-radio-button :label="1">未绑定</el-radio-button>
            <el-radio-button :label="2">已绑定</el-radio-button>
          </el-radio-group>
        </el-col>
        <el-col :span="16" style="display: flex; float: right">
          <el-input
            v-model="value"
            clearable
            size="small"
            placeholder="输入名称搜索"
            prefix-icon="el-icon-search"
            style="margin-right: 10px"
          ></el-input>
          <el-input
            v-model="value2"
            clearable
            size="small"
            placeholder="输入电话搜索"
            prefix-icon="el-icon-search"
            style="margin-right: 10px"
          ></el-input>
          <el-button type="primary" @click="dialogSearch">搜索</el-button>
        </el-col>
      </el-row>
      <HHtable
        ref="table2"
        :border="true"
        :height="300"
        :check-box="true"
        :total="total2"
        :table-data="tableData2"
        :table-column="tableColumn2"
        @page-click="pageClick2"
        @selection-change="handleSelectionChange"
      ></HHtable>
      <div class="dialog-bottom flex flex-center flex-wrap">
        <el-button type="primary" @click="bindOrUnbindRelation">
          {{ name }}
        </el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import HHsearch from '@/components/HH-search'
  import HHtable from '@/components/HH-table'
  import Modal from '@/components/HH-modal'
  import { splicingUrl, imageUrl } from '@/utils/validate'
  import {
    getCounselor,
    getCounselorDown,
    exportCounselor,
    remarkEdit,
  } from '@/api/conunselor.js'
  import { getDistributorList } from '@/api/distribution'
  import { freezeCounselor, bindrelationship } from '@/api/common'
  export default {
    name: 'Index',
    components: {
      HHsearch,
      HHtable,
      Modal,
    },
    data() {
      const formatter = function (row, column, cellValue, index) {
        if (cellValue == 2) return '冻结'
        return '正常'
      }
      return {
        showFreezeModal: false,
        showUnfreezeModal: false,
        dialogVisible: false,
        radio: 2,
        value: '',
        value2: '',
        value3: '',
        total: 0,
        total2: 0,
        origin: [
          {
            value: '44S',
            label: '东莞',
          },
          {
            value: '44T',
            label: '中山',
          },
          {
            value: '44E',
            label: '佛山',
          },
          {
            value: '44J',
            label: '江门',
          },
          {
            value: '43A',
            label: '长沙',
          },
          {
            value: '44A',
            label: '广州',
          },
          {
            value: '44K',
            label: '茂名',
          },
          {
            value: '44V',
            label: '揭阳',
          },
          {
            value: '44F',
            label: '韶关',
          },
          {
            value: '44R',
            label: '清远',
          },
        ],
        searchOptions: [
          {
            type: 'select',
            prop: 'status',
            label: '状态：',
            span: 5,
            placeholder: '请选择',
            arr: [
              {
                value: '',
                label: '全部招生顾问',
              },
              {
                value: 1,
                label: '正常招顾',
              },
              {
                value: 2,
                label: '冻结招顾',
              },
            ],
          },
          {
            type: 'select',
            prop: 'region',
            label: '地区：',
            span: 5,
            placeholder: '请选择',
            arr: [],
          },
          {
            type: 'text',
            prop: 'userName',
            span: 6,
            label: '招生顾问名称：',
            placeholder: '选择或输入搜索',
          },
          {
            type: 'text',
            prop: 'phone',
            label: '手机号：',
            span: 5,
            placeholder: '选择或输入搜索',
          },
          {
            type: 'daterange',
            prop: 'daterange',
            label: '成为招顾日期：',
            span: 8,
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期',
            valueFormat: 'yyyy-MM-dd',
          },
        ],
        tableColumn: [
          {
            prop: 'dcName',
            label: '招生顾问名称',
          },
          {
            prop: 'mobilePhone',
            label: '手机号码',
          },
          {
            label: '微信二维码',
            slotContent: 'codeSlot',
          },
          {
            prop: 'subordinate',
            label: '下级人数',
          },
          {
            prop: 'branchSchool',
            label: '所属地区',
          },
          {
            prop: 'createTime',
            label: '添加时间',
          },
          {
            prop: 'status',
            label: '分销状态',
            formatter: formatter,
          },
          // {
          //   prop: 'totalMoney',
          //   width: 150,
          //   label: '相关订单金额（元）',
          // },
          // {
          //   prop: 'integral',
          //   label: '累计积分',
          // },
          {
            prop: 'remarks',
            label: '备注',
            width: 150,
            slotContent: 'remarkSlot',
          },
        ],
        tableData: [],
        btnOption: [
          {
            type: 'primary',
            size: 'mini',
            text: '查看信息',
            except: 3,
            show: true,
            func: this.edit,
          },
          {
            type: 'info',
            size: 'mini',
            text: '冻结分销',
            except: 2,
            show: true,
            func: this.handleFreeze,
          },
          {
            type: 'warning',
            size: 'mini',
            text: '解冻分销',
            except: 1,
            show: true,
            func: this.handleUnfreeze,
          },
          {
            type: 'danger',
            size: 'mini',
            text: '修改关系',
            except: 3,
            show: true,
            func: this.handleChangeRelation,
          },
        ],
        dialogColumn: [],
        dialogData: [],
        params: {
          pageSize: 10,
          pageNumber: 1,
          queryCriteria: {
            userName: '',
            status: '',
            startTime: '',
            endTime: '',
            phone: '',
            region: '',
          },
        },
        params2: {
          pageNumber: 1,
          pageSize: 10,
          queryCriteria: {
            cellphone: '',
            spoorerId: '',
            username: '',
          },
        },
        params3: {
          pageSize: 10,
          pageNumber: 1,
          status: '',
          userName: '',
          cellphone: '',
          inviteUser: '',
          startTime: '',
          endTime: '',
          upid: '',
          notupid: 2,
        },
        tableColumn2: [
          {
            prop: 'username',
            label: '分销员名称',
          },
          {
            prop: 'cellphone',
            label: '手机号码',
          },
        ],
        tableData2: [],
        counselorInfo: {},
        selectionId: '',
        selectionUserName: '',
        regionObj: {
          '44S': { value: '44S', label: '东莞' },
          '44T': { value: '44T', label: '中山' },
          '44E': { value: '44E', label: '佛山' },
          '44J': { value: '44J', label: '江门' },
          '43A': { value: '43A', label: '长沙' },
          '44A': { value: '44A', label: '广州' },
          '44K': { value: '44K', label: '茂名' },
          '44V': { value: '44V', label: '揭阳' },
          '44F': { value: '44F', label: '韶关' },
          '44R': { value: '44R', label: '清远' },
        },
        topArray: ['S22', 'S52', '1368', 'S68'],
        user: JSON.parse(localStorage.getItem('user')) || '',
      }
    },
    computed: {
      name() {
        if (this.radio == 2) {
          return '解除绑定'
        } else {
          return '绑定关系'
        }
      },
    },
    mounted() {
      const user = JSON.parse(localStorage.getItem('user'))
      if (this.topArray.includes(user.username.toUpperCase())) {
        this.searchOptions[1].arr = Object.values(this.regionObj)
      } else {
        this.searchOptions[1].arr.push(this.regionObj[user.branchcampus])
        this.params.queryCriteria.region =
          this.regionObj[user.branchcampus].value
      }
      this.getList()
    },
    methods: {
      edit(res) {
        this.$router.push({
          path: `/detail/${res.id}`,
          query: { identity: 2 },
        })
      },
      getList() {
        this.$refs.table.loading = true
        getCounselor(this.params)
          .then((res) => {
            if (res.code === 200) {
              const arr = res.data.list
              arr.forEach((item) => {
                if (item.imgUrl) item.imgUrl = imageUrl(item.imgUrl)
                if (item.wxCode) item.wxCode = imageUrl(item.wxCode)
                item.isShow = true
              })
              this.tableData = arr
              this.total = res.data.total
              setTimeout(() => {
                this.$refs.table.loading = false
              }, 1000)
            } else {
              this.$baseMessage(res.msg, 'error')
            }
          })
          .catch((error) => {
            setTimeout(() => {
              this.$refs.table.loading = false
            }, 1000)
          })
      },
      handleFreeze(res) {
        this.showFreezeModal = true
        this.counselorInfo = res
      },
      handleUnfreeze(res) {
        this.showUnfreezeModal = true
        this.counselorInfo = res
      },
      confirmFreeze(status) {
        let params = {
          status,
          id: this.counselorInfo.id.toString(),
        }
        freezeCounselor(params).then((res) => {
          if (res.code === 200) {
            this.getList()
            this.showFreezeModal = false
            this.showUnfreezeModal = false
            let msg = '冻结成功'
            if (status === 2) msg = '解冻成功'
            this.$baseMessage(msg, 'success')
          } else {
            this.$baseMessage(res.msg, 'error')
          }
        })
      },
      search(res) {
        if (res.daterange) {
          res.startTime = res.daterange[0]
          res.endTime = res.daterange[1]
          delete res.daterange
        }
        const arr = Object.keys(res)
        for (let i = 0; i < arr.length; i++) {
          this.params.queryCriteria[arr[i]] = res[arr[i]]
        }
        this.getList()
      },
      reset() {
        this.params = {
          pageSize: 10,
          pageNumber: 1,
          queryCriteria: {
            userName: '',
            status: '',
            phone: '',
            startTime: '',
            endTime: '',
          },
        }
        this.$refs.search.removeFilterArray()
        this.getList()
      },
      handleExport(res) {
        const param = {
          userName: '',
          status: '',
          phone: '',
          startTime: '',
          endTime: '',
        }
        if (res.daterange) {
          param.startTime = res.daterange[0]
          param.endTime = res.daterange[1]
          delete res.daterange
        }
        const arr = Object.keys(param)
        for (let i = 0; i < arr.length; i++) {
          param[arr[i]] = res[arr[i]] || ''
        }
        let url = splicingUrl(param)
        const link = document.createElement('a')
        link.style.display = 'none'
        link.href = this.baseURL + '/distributionConsul/export.do?' + url
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      },
      handleChangeRelation(res) {
        this.dialogVisible = true
        this.counselorInfo = res
        this.params2.queryCriteria.spoorerId = this.counselorInfo.id
        getCounselorDown(this.params2).then((res) => {
          this.$refs.table2.loading = true
          if (res.code == 200) {
            this.tableData2 = res.data.list
            this.total2 = res.data.total
            setTimeout(() => {
              this.$refs.table2.loading = false
            }, 1000)
          } else {
            this.$baseMessage(res.msg, 'error')
          }
        })
      },
      handleRadioChange() {
        this.value2 = ''
        this.value = ''
        this.$refs.table2.loading = true
        if (this.radio == 1) {
          // this.params3.spoorerid = JSON.parse(
          //   localStorage.getItem('user')
          // ).oprationId
          getDistributorList(this.params3).then((res) => {
            if (res.code === 200) {
              this.tableData2 = res.data.list
              this.total2 = res.data.total
              setTimeout(() => {
                this.$refs.table2.loading = false
              }, 1000)
            }
          })
        } else {
          this.params2.queryCriteria.spoorerId = this.counselorInfo.id
          getCounselorDown(this.params2).then((res) => {
            if (res.code == 200) {
              this.tableData2 = res.data.list
              this.total2 = res.data.total
              setTimeout(() => {
                this.$refs.table2.loading = false
              }, 1000)
            } else {
              this.$baseMessage(res.msg, 'error')
            }
          })
        }
      },
      pageClick(pager) {
        this.params.pageNumber = pager
        this.getList()
      },
      pageClick2(pager) {
        this.params2.pageNumber = pager
        this.params3.pageNumber = pager
        this.handleRadioChange()
      },
      dialogSearch() {
        this.$refs.table2.loading = true
        // 查询分销员
        if (this.radio == 1) {
          this.params3.userName = this.value
          this.params3.cellphone = this.value2
          // this.params3.spoorerid = JSON.parse(
          //   localStorage.getItem('user')
          // ).oprationId
          getDistributorList(this.params3).then((res) => {
            if (res.code === 200) {
              this.tableData2 = res.data.list
              this.total2 = res.data.total
              setTimeout(() => {
                this.$refs.table2.loading = false
              }, 1000)
            } else {
              this.$baseMessage(res.msg, 'error')
            }
          })
        } else {
          // 查询招顾下级
          this.params2.queryCriteria.username = this.value
          this.params2.queryCriteria.cellphone = this.value2
          getCounselorDown(this.params2).then((res) => {
            if (res.code == 200) {
              this.tableData2 = res.data
              this.total2 = res.data.length
              setTimeout(() => {
                this.$refs.table2.loading = false
              }, 1000)
            } else {
              this.$baseMessage(res.msg, 'error')
            }
          })
        }
      },
      handleSelectionChange(res) {
        const arr = []
        const arr2 = []
        res.forEach((item) => {
          arr.push(item.id)
          arr2.push(item.username)
        })
        this.selectionId = arr.join(',')
        this.selectionUserName = arr2.join(',')
      },
      bindOrUnbindRelation() {
        if (this.selectionUserName.length < 1 || this.selectionId.length < 1) {
          this.$baseMessage('请选择操作人', 'warning')
          return
        }
        let params = {
          id: this.counselorInfo.id,
          idStr: this.selectionId,
          dcName: this.counselorInfo.userName,
          dcNameStr: this.selectionUserName,
          type: this.radio,
          oprationName: this.user.name,
          oprationId: this.user.oprationId,
        }
        bindrelationship(params).then((res) => {
          if (res.code === 200) {
            this.$baseMessage(res.msg, 'success')
            this.handleRadioChange()
          } else {
            this.$baseMessage(res.msg, 'error')
          }
        })
      },
      editRemark(data) {
        this.tableData.map((item) => {
          item.isShow = true
        })
        data.isShow = false
        this.value3 = data.remarks
      },
      saveRemark(data) {
        data.isShow = true
        const params = {
          id: data.id,
          remarks: this.value3,
        }
        remarkEdit(params)
          .then((res) => {
            if (res.code === 200) {
              this.$baseMessage('修改成功', 'success')
              this.value3 = ''
              this.getList()
            } else {
              this.$baseMessage(res.msg, 'error')
            }
          })
          .catch((error) => {
            this.value3 = ''
          })
      },
    },
  }
</script>
<style lang="scss" scoped>
  @import './../../assets/styles/common.css';
  @import './../../assets/styles/dialog.scss';
  .imgs {
    width: 100px;
    height: 100px;
    object-fit: contain;
    border-radius: 0;
  }

  .dialog-bottom {
    margin-top: 30px;
  }
  ::v-deep {
    .el-dialog__wrapper {
      overflow: hidden;
    }
    .remark-edit {
      flex-direction: column;
      .el-input__inner {
        border: none;
      }
      img {
        margin-left: auto;
        vertical-align: middle;
      }
    }
  }
</style>
